﻿using SuperX.Common.Log;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SuperX.Helper.NOPI
{
    public class ListTableTools
    {
        /// <summary>
        /// List集合转DataTable
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="list">传入集合</param>
        /// <param name="isStoreDB">是否存入数据库DateTime字段，date时间范围没事，取出展示不用设置TRUE</param>
        /// <returns>返回datatable结果</returns>
        public static DataTable ListToTable<T>(List<T> list, string Skips = "", bool isStoreDB = true)
        {
            Type tp = typeof(T);
            PropertyInfo[] proInfos = tp.GetProperties();
            DataTable dt = new DataTable();
            foreach (var item in proInfos)
            {
                if (Skips.Split(',').Contains(item.Name)) continue;
                dt.Columns.Add(item.Name, item.PropertyType); //添加列明及对应类型
            }
            foreach (var item in list)
            {
                DataRow dr = dt.NewRow();
                foreach (var proInfo in proInfos)
                {
                    if (Skips.Split(',').Contains(proInfo.Name)) continue;
                    object obj = proInfo.GetValue(item, null);
                    if (obj == null)
                    {
                        continue;
                    }
                    if (isStoreDB && proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
                    {
                        continue;
                    }
                    dr[proInfo.Name] = obj;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// DataTable转化为List集合
        /// </summary>
        /// <typeparam name="T">实体对象</typeparam>
        /// <param name="dt">datatable表</param>
        /// <returns>返回list集合</returns>
        public static List<T> TableToList<T>(DataTable dt, out StringBuilder msg, string Skips = "")
        {
            List<T> list = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] pArray = type.GetProperties(); //集合属性数组
            msg = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                T entity = Activator.CreateInstance<T>(); //新建对象实例
                foreach (PropertyInfo p in pArray)
                {
                    if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value || Skips.Split(',').Contains(p.Name))
                        continue;
                    try
                    {
                        if (p.PropertyType.IsEnum)
                            p.SetValue(entity, Enum.Parse(p.PropertyType, row[p.Name].ToString()), null);
                        else
                            p.SetValue(entity, Convert.ChangeType(row[p.Name].ToString(), p.PropertyType, CultureInfo.CreateSpecificCulture("en-US")), null);
                    }
                    catch (Exception ex)
                    {
                        msg.AppendLine($"在分组{dt.TableName}-行{dt.Rows.IndexOf(row) + 2}-{p.Name}:【{row[p.Name]}】字段中出现错误。");
                        Logger.ErrorException(ex);
                    }
                }
                list.Add(entity);
            }
            return list;
        }
    }
}